package nl.weeaboo.sh.view;

import java.awt.Point;
import java.awt.Rectangle;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import nl.weeaboo.game.ResourceManager;
import nl.weeaboo.game.gl.GLImage;
import nl.weeaboo.sh.io.CharaImageLoader;
import nl.weeaboo.sh.model.CharaImageModel;

import org.xml.sax.SAXException;

import timon.common.Log;
import timon.common.io.FileUtil;

public class CharaImageStore {

	private ResourceManager resourceManager;
	private Map<String, CharaImage> map;
	
	public CharaImageStore() {
		map = new HashMap<String, CharaImage>();
	}
	
	//Functions
	public void add(String id, CharaImage ci) {
		map.put(id, ci);
	}
	
	public void load(ResourceManager rm) {
		resourceManager = rm;
		
		CharaImageLoader loader = new CharaImageLoader();
		String folderName = "chara_images";
		
		Set<String> files = resourceManager.getFolderContents(folderName);
		for (String file : files) {
			if (FileUtil.getExtension(file).equals("xml")) {				
				try {
					Collection<CharaImageModel> imgs = loader.load(
							resourceManager.getInputStream(file));
					String imagePath = loader.getImagePath();
					Rectangle levelRect = loader.getLevelRect();
					for (CharaImageModel ci : imgs) {						
						GLImage image = resourceManager.getImageStore()
							.getImage(imagePath, true).derive(rm.getImageStore(),
								ci.id, ci.anchor.x+ci.imageBounds.x, ci.anchor.y+ci.imageBounds.y,
								ci.imageBounds.width, ci.imageBounds.height);
						Point imageOffset = new Point(ci.imageBounds.x, ci.imageBounds.y);
						add(imagePath+'#'+ci.id,
							new CharaImage(ci.id, image, imageOffset, levelRect,
								ci.hitRects, ci.damageRects, ci.splashRects, ci.colCircles));
					}
				} catch (SAXException e) {
					Log.error(e);
				} catch (IOException e) {
					Log.error(e);
				}
			}
		}
	}
	
	public void unloadGLImages() {
		for (CharaImage img : map.values()) {
			img.setImage(null);
		}
	}
	public void clear() {
		map.clear();
	}
	
	//Getters
	public CharaImage getImage(String id) {
		CharaImage ci = map.get(id);
		if (ci != null) {
			ci.setImage(resourceManager.getImageStore().getImage(id, true));
		}
		return ci;
	}
	
	//Setters
	
}
